package com.codedef.diary;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.codedef.diary.config.HandlerInfo;
import com.codedef.diary.config.SharedConfig;
import com.codedef.diary.config.UrlConfig;
import com.codedef.diary.domain.Diary;
import com.codedef.diary.domain.User;
import com.codedef.diary.util.DateUtil;
import com.codedef.diary.util.DiaryUtil;
import com.codedef.diary.util.NetWorkUtil;
import com.codedef.diary.util.UserUtil;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class DiaryListActivity extends AppCompatActivity {

    private static final int SET_DIARIES = 10001;
    private static final int SET_USERINFO = 10002;

    DiaryAdapter adapter;
    List<Diary> diaries;
    ListView listView;
    Toolbar toolbar;
    FloatingActionButton fab;
    NavigationView navigationView;
    View headerLayout;

    private DrawerLayout mDrawerLayout;

    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HandlerInfo.MAKE_TOAST:
                    Toast.makeText(DiaryListActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case SET_DIARIES:
                    diaries.clear();
                    diaries.addAll((List<Diary>) msg.obj);
                    adapter.notifyDataSetChanged();
                    break;
                case SET_USERINFO:
                    User user = (User) msg.obj;

                    headerLayout = navigationView.getHeaderView(0);
                    CircleImageView circleImage = headerLayout.findViewById(R.id.head_img);
                    TextView tvId = headerLayout.findViewById(R.id.userid);
                    tvId.setText("ID: " + user.getId());
                    TextView tvUsername = headerLayout.findViewById(R.id.username);
                    tvUsername.setText(" 欢迎您!");

                    Menu menu = navigationView.getMenu();
                    String g = user.getGender().intValue() == 1 ? "男" : "女";
                    menu.findItem(R.id.nav_user).setTitle("用户名：" + user.getUsername());
                    menu.findItem(R.id.nav_gender).setTitle("性别：" + g);
                    menu.findItem(R.id.nav_birthday).setTitle("生日：" + user.getBirthday().toString());


                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary_list);
        initData();
        initUi();

    }

    @Override
    protected void onResume() {
        super.onResume();
        requestDiarys();
    }

    private void initUi() {
        //ToolBar
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mDrawerLayout = findViewById(R.id.draw_layout);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.menu);
        }
        //悬浮按钮
        fab = findViewById(R.id.flt_btn);

        listView = findViewById(R.id.list_diary);
        adapter = new DiaryAdapter(DiaryListActivity.this, R.layout.diary_item, diaries);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Diary diary = diaries.get(position);
                Intent intent = new Intent(DiaryListActivity.this, NewDiaryActivity.class);
                intent.putExtra("DIARY", diary);
                intent.putExtra("FLAG", "OLD");
                startActivity(intent);
            }
        });
        // navigationView
        navigationView = findViewById(R.id.nav_view);


    }

    private void initData() {
        diaries = new ArrayList<>();
        requestDiarys();
        loadUserInfo();
    }

    // 请求网络数据
    private void requestDiarys() {
        SharedPreferences sp = getSharedPreferences(SharedConfig.SHARED_MODEL_NAME, Context.MODE_PRIVATE);
        final String session = sp.getString(SharedConfig.KEY_SESSION, null);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = null;
                result = NetWorkUtil.get(UrlConfig.diaries, session);
                Message msg = new Message();
                msg.what = SET_DIARIES;
                List<Diary> list = DiaryUtil.getDiaryListByJsonArrayStr(result);
                Log.e("shy", list.toString());
                msg.obj = list;
                handler.sendMessage(msg);
            }
        }).start();
    }

    // 从网络获取用户信息
    private void loadUserInfo() {
        SharedPreferences sp = getSharedPreferences(SharedConfig.SHARED_MODEL_NAME, Context.MODE_PRIVATE);
        final String session = sp.getString(SharedConfig.KEY_SESSION, null);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = NetWorkUtil.get(UrlConfig.USER_INFO, session);
                Log.e("shy", result);
                User user = UserUtil.getUserByJson(result);
                Message message = new Message();
                message.what = SET_USERINFO;
                message.obj = user;
                handler.sendMessage(message);
            }
        }).start();
    }

    //悬浮按钮的点击事件
    public void onFloatButtonClick(View view) {
        Intent intent = new Intent(DiaryListActivity.this, NewDiaryActivity.class);
        intent.putExtra("FLAG", "NEW");
        startActivity(intent);
    }

    //建立toolbar菜单栏
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.toolbar,menu);
        return true;
    }

    //toolbar菜单选择
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.search:
                Toast.makeText(this,"You clicked  Backup",Toast.LENGTH_SHORT).show();
                break;
            case R.id.exit:
                Toast.makeText(this,"You clicked  Deleted",Toast.LENGTH_SHORT).show();
                break;
            case R.id.settings:
                Toast.makeText(this,"You clicked  setting",Toast.LENGTH_SHORT).show();
                break;
            default:
        }

        return true;
    }

}
